package com.ruoyi.finance.service.impl;

import com.ruoyi.IndexDtoByThree;
import com.ruoyi.activiti.api.RemoteActivitiService;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.finance.dto.IndexReceiveReqDto;
import com.ruoyi.finance.mapper.ReciveReqMapper;
import com.ruoyi.finance.service.IReciveReqService;
import com.ruoyi.system.api.constants.BuyBackOrderConstants;
import com.ruoyi.system.api.domain.finance.ReciveReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 应收需求单Service业务层处理
 *
 * @author wl
 * @date 2024-11-01
 */
@Service
@Slf4j
public class ReciveReqServiceImpl implements IReciveReqService {
    @Autowired
    private ReciveReqMapper reciveReqMapper;

    @Autowired
    private RemoteActivitiService remoteActivitiService;

    /**
     * 查询应收需求单
     *
     * @param id 应收需求单主键
     * @return 应收需求单
     */
    @Override
    public ReciveReq selectReciveReqById(Integer id) {
        return reciveReqMapper.selectReciveReqById(id);
    }

    @Override
    public IndexDtoByThree getReceiveReqThreeCountToIndex() {
        return reciveReqMapper.getReceiveReqThreeCountToIndex();
    }

    @Override
    public BigDecimal getAllAmount() {
        return reciveReqMapper.getAllAmount();
    }

    /**
     * @return com.ruoyi.system.api.domain.finance.ReciveReq
     * @description 根据财务应收单编号获取详情
     * @date 2024/11/10 下午11:10
     * @Param orderCode:
     **/
    public ReciveReq getReciveReqByOrderCode(String orderCode) {
        return reciveReqMapper.selectReciveReqByOrderCode(orderCode);
    }

    /**
     * @return com.ruoyi.common.core.web.domain.AjaxResult
     * @description 根据应收单编号修改，sql语句修改已核销金额
     * @date 2024/11/19 上午9:24
     * @Param reciveReq:
     **/
    public AjaxResult updateReciveOrderByOrderCodeOfVerMoney(ReciveReq reciveReq) {
        int updNum = reciveReqMapper.updateReciveOrderByOrderCodeOfVerMoney(reciveReq);
        log.info("updateReciveOrderByOrderCodeOfVerMoney updNum:{}", updNum);
        return AjaxResult.success();
    }

    /**
     * 查询应收需求单列表
     *
     * @param reciveReq 应收需求单
     * @return 应收需求单
     */
    @Override
    public List<ReciveReq> selectReciveReqList(ReciveReq reciveReq) {
        List<ReciveReq> reciveReqList = reciveReqMapper.selectReciveReqList(reciveReq);
        for (ReciveReq reciveReqParam : reciveReqList) {
            reciveReqParam.setNoMoney(reciveReqParam.getMoney().subtract(reciveReqParam.getVerMoney()));
        }
        return reciveReqList;
    }

    @Override
    public IndexReceiveReqDto getSaleOrderReciveCountAndMoney() {
        return reciveReqMapper.getSaleOrderReciveCountAndMoney();
    }

    @Override
    public IndexReceiveReqDto getBuyBackReciveCountAndMoney() {
        return reciveReqMapper.getBuyBackReciveCountAndMoney();
    }

    /**
     * 新增应收需求单
     *
     * @param reciveReq 应收需求单
     * @return 结果
     */
    @Transactional
    public AjaxResult insertReciveReq(ReciveReq reciveReq) {
        //校验单据编号
        if (StringUtils.isBlank(reciveReq.getOrderCode())) {
            return AjaxResult.error("单据编号不能为空");
        }
        int count = reciveReqMapper.selectCountReciveReqByOrderCode(reciveReq.getOrderCode());
        if (count > 0) {
            return AjaxResult.error("单据编号已存在");
        }
        //校验单据日期
        if (reciveReq.getOrderDate() == null) {
            return AjaxResult.error("单据日期不能为空");
        }
        //校验金额
        if (reciveReq.getMoney() == null || reciveReq.getMoney().compareTo(BigDecimal.ZERO) <= 0) {
            return AjaxResult.error("金额不能为空且必须大于0");
        }
        //校验应收单类型
        if (reciveReq.getPaymentType() == null) {
            return AjaxResult.error("应收单类型不能为空");
        }
        //状态初始化
        if (reciveReq.getOrderStatus() == null) {
            reciveReq.setOrderStatus(BuyBackOrderConstants.ORDER_STATUS_SUBMITTED);
        }
        if (reciveReq.getIsEffect() == null) {
            reciveReq.setIsEffect(0);
        }
        reciveReq.setVerMoney(BigDecimal.ZERO);
        reciveReq.setIsClose(0);
        reciveReq.setIsCancel(0);
        reciveReq.setCreateBy(SecurityUtils.getUsername());
        reciveReq.setCreateDate(new Date());
        reciveReq.setIsDel(0);

        //插入数据库
        int addNum = reciveReqMapper.insertReciveReq(reciveReq);
        log.info("ReciveReqServiceImpl insertReciveReq addNum:{}", addNum);
        if (addNum <= 0) {
            return AjaxResult.error("新增失败!");
        }

        //如果是其他应收单则生成待审核任务
//        if (reciveReq.getPaymentType() == 103) {
//            //添加审核任务
//            ActApprovalDTO actApprovalDTO = new ActApprovalDTO();
//            actApprovalDTO.setProcessDefinitionKey("reciveReqBPMN");
//            actApprovalDTO.setOrderCode(reciveReq.getOrderCode());
//            actApprovalDTO.setTaskName(reciveReq.getOrderCode() + "采购退货申请");
//            //财务经理部门id
//            actApprovalDTO.setDeptId(103);
//            AjaxResult addApprovalAjaxResult = remoteActivitiService.addApproval(actApprovalDTO);
//            Integer code = (Integer) addApprovalAjaxResult.get("code");
//            if (code != 200) {
//                throw new RuntimeException("新增失败");
//            }
//        }

        return AjaxResult.success();
    }

    /**
     * 修改应收需求单
     *
     * @param reciveReq 应收需求单
     * @return 结果
     */
    @Transactional
    public AjaxResult updateReciveReq(ReciveReq reciveReq) {
        //校验单据主键
        if (reciveReq.getId() == null) {
            return AjaxResult.error("应收单id不能为空");
        }
        //校验单据日期
        if (reciveReq.getOrderDate() == null) {
            return AjaxResult.error("单据日期不能为空");
        }
        //校验金额
        if (reciveReq.getMoney() == null || reciveReq.getMoney().compareTo(BigDecimal.ZERO) <= 0) {
            return AjaxResult.error("金额不能为空且必须大于0");
        }
        //状态初始化
        if (reciveReq.getOrderStatus() == null) {
            reciveReq.setOrderStatus(BuyBackOrderConstants.ORDER_STATUS_SUBMITTED);
        }
        if (reciveReq.getIsEffect() == null) {
            reciveReq.setIsEffect(0);
        }
        reciveReq.setModifyBy(SecurityUtils.getUsername());
        reciveReq.setModifyDate(new Date());

        //插入数据库
        int updNum = reciveReqMapper.updateReciveReq(reciveReq);
        log.info("ReciveReqServiceImpl insertReciveReq updNum:{}", updNum);
        if (updNum > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改失败!");
    }

    /**
     * 批量删除应收需求单
     *
     * @param ids 需要删除的应收需求单主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteReciveReqByIds(Integer[] ids) {
        int delNum = reciveReqMapper.deleteReciveReqByIds(ids);
        log.info("ReciveReqServiceImpl deleteReciveReqByIds delNum:{}", delNum);
        if (delNum > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("删除失败!");
    }

    /**
     * 删除应收需求单信息
     *
     * @param id 应收需求单主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteReciveReqById(Integer id) {
        int delNum = reciveReqMapper.deleteReciveReqById(id);
        log.info("ReciveReqServiceImpl deleteReciveReqById delNum:{}", delNum);
        if (delNum > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("删除失败!");
    }

    /**
     * @return com.ruoyi.common.core.web.domain.AjaxResult
     * @description 校验收款需求单编号
     * @date 2024/11/1 上午9:29
     * @Param orderCode:
     **/
    public AjaxResult checkReciveReqOrderCode(String orderCode) {
        //
        if (StringUtils.isBlank(orderCode)) {
            return AjaxResult.error("单据编号不能为空");
        }
        int count = reciveReqMapper.selectCountReciveReqByOrderCode(orderCode);
        log.info("ReciveReqServiceImpl checkReciveReqOrderCode orderCode:{},count:{}", orderCode, count);
        if (count > 0) {
            return AjaxResult.error("单据编号已存在");
        }
        return AjaxResult.success();
    }

    /**
     * @return com.ruoyi.common.core.web.domain.AjaxResult
     * @description 审核后修改财务应收单
     * @date 2024/11/10 下午10:32
     * @Param reciveReq:
     **/
    public AjaxResult updateReciveStatus(ReciveReq reciveReq) {
        //校验财务应收单编号
        if (reciveReq.getOrderCode() == null) {
            return AjaxResult.error("应收单编号不能为空");
        }

        //如果审核通过设置为生效，以及生效日期
        if (reciveReq.getApprovalResult() == 2) {
            reciveReq.setIsEffect(1);
            reciveReq.setEffectDate(new Date());
        }

        //如果审核不通过关闭财务应收单
        if (reciveReq.getApprovalResult() == 3) {
            reciveReq.setIsClose(1);
        }

        //修改单据状态为已审批：3
        reciveReq.setOrderStatus(BuyBackOrderConstants.ORDER_STATUS_APPROVED);
        //设置审核人
        reciveReq.setApprovalId(Math.toIntExact(SecurityUtils.getUserId()));
        //设置修改人 修改时间
        reciveReq.setModifyBy(SecurityUtils.getUsername());
        reciveReq.setModifyDate(new Date());

        //调用根据财务应收单编号修改财务应收单
        int updNum = reciveReqMapper.updateReciveReqByOrderCode(reciveReq);
        log.info("ReciveReqServiceImpl updateReciveStatus updNum:{}", updNum);
        if (updNum < 0) {
            return AjaxResult.error("修改失败!");
        }

        return AjaxResult.success();
    }
}
